using System.Text.Json;
using LetCoding.CodeApi.Models;
using LetCoding.CodeApi.Services;
using Microsoft.AspNetCore.Mvc;

namespace LetCoding.CodeApi.Controllers;

[ApiController]
[Route("[controller]")]
public class RunController(GlotService service, IConfiguration configuration)
    : ControllerBase
{
    [HttpPost]
    public async Task<ActionResult<RunResult>> Post([FromBody] RunRequestModel model)
    {
        var apiToken = Environment.GetEnvironmentVariable("API_TOKEN", EnvironmentVariableTarget.Process);
        if (string.IsNullOrEmpty(apiToken))
        {
            apiToken = configuration["ApiToken"] ?? "";
        }

        if (string.IsNullOrEmpty(apiToken))
        {
            return new BadRequestObjectResult("请配置API_TOKEN环境变量或ApiToken配置项。");
        }

        var result = await service.RunGlotAsync(apiToken, model.Code, model.Language, model.Stdin);

        return Ok(result);
    }
}